import 'package:flutter/material.dart';
import 'package:flutter_image/network.dart';
import 'package:flutter_mwm/base/base.dart';
import 'package:flutter_mwm/beans/bean.dart';
import 'package:flutter_mwm/impl/http.dart';
import 'package:flutter_mwm/ui/qrcode.dart';
import 'package:flutter_mwm/util/util.dart';
import 'package:flutter_mwm/widget/edit.dart';
import 'package:flutter_mwm/widget/text.dart';
import 'package:flutter_mwm/widget/widget.dart';
import 'package:flutter_mwm/impl/impl.dart';

class PersonalHome extends BaseWidget<PersonalHome> {
  final AccountBean accountBean;

  const PersonalHome({this.accountBean});

  @override
  State<StatefulWidget> createState() {
    return _StatePersonal();
  }
}

class _StatePersonal extends StateBase<PersonalHome>
    implements HttpCallbackImpl {
  var username = '', nickName = '', signature = "", iconUrl = '';
  TextEditingController nickNameController = new TextEditingController();
  TextEditingController signController = new TextEditingController();

  @override
  void initState() {
    AccountBean accountBean = widget.accountBean;
    if (null != accountBean) {
      username = accountBean.username;
      signature = accountBean.signature;
      nickName = accountBean.nickname;
      signature = TextUtils.isEmpty(signature) ? '这个人很懒...' : signature;
      nickName = TextUtils.isEmpty(nickName) ? username : nickName;
      nickNameController.text = nickName;
      signController.text = TextUtils.isEmpty(signature) ? "" : signature;
    }
    super.initState();
    showAvatar();
  }

  var _actionEdit = false;

  Future<Null> showAvatar() async {
    iconUrl = await HttpKit.getInstance()
        .getIcon(method: 'showAvatar', username: username);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('个人资料'),
        backgroundColor: Color(0xFF051728),
        centerTitle: true,
        actions: <Widget>[_actionView()],
      ),
      backgroundColor: Colors.grey[200],
      body: Container(
          child: Column(
        children: <Widget>[
          Container(
              alignment: Alignment.center,
              child: _iconView(),
              margin: EdgeInsets.only(top: 48.0)),
          Container(
            color: Colors.white,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                _topLeftTextView('账号'),
                _bottomRightTextView(username),
                _lineView(),
                _topLeftTextView('昵称'),
                _bottomNickNameView(nickName),
                _lineView(),
                _topLeftTextView('签名'),
                _bottomSignView(signature),
                _lineView(),
                _topLeftTextView('名片'),
                _bottomQrView(),
              ],
            ),
          ),
        ],
      )),
    );
  }

/*appBar右侧编辑栏*/
  Widget _actionView() {
    return ClickLayout(
      onPressed: () => _edit(),
      child: Container(
        child: Icon(_actionEdit ? Icons.save : Icons.edit),
        padding: EdgeInsets.only(left: 8.0, right: 8.0),
        margin: EdgeInsets.only(right: 10.0),
        alignment: Alignment.center,
      ),
    );
  }

  void _edit() {
    setState(() {
      if (_actionEdit) {
        _update();
      } else {
        _actionEdit = true;
      }
    });
  }

  /*修改信息*/
  void _update() {
    if (TextUtils.isEmpty(username)) {
      ToastUtil.show(context, '用户名不能为空！');
      return;
    }
    String nickName = nickNameController.text;
    nickName = TextUtils.isEmpty(nickName) ? username : nickName;
    String signature = signController.text;
    AccountBean accountBean = AccountBean(
        username: username, nickname: nickName, signature: signature);
    Map<String, String> bodyParams = {
      'beanJson': GsonUtil.bean2Json(accountBean)
    };
    var http = HttpKit.getInstance(context: context, what: 4, tag: accountBean);
    http.callback(this);
    http.execute(method: 'updateUser', paramBody: bodyParams);
  }

/*appBar右侧编辑栏*/
  Widget _iconView() {
    return CircleAvatar(
        radius: 50.0,
        backgroundImage: _avatarIcon(),
        backgroundColor: Colors.green);
  }

  ImageProvider _avatarIcon() {
    return TextUtils.isEmpty(username) || TextUtils.isEmpty(iconUrl)
        ? AssetImage('images/icon.png')
        : NetworkImageWithRetry(iconUrl);
  }

  Widget _topLeftTextView(String text) {
    return TextView(
      text,
      textAlign: TextAlign.left,
      textSize: 18,
      textColor: Colors.black,
      margin: EdgeInsets.only(top: 8),
      padding: EdgeInsets.symmetric(horizontal: 8),
    );
  }

  /*横线*/
  Widget _lineView() {
    return Line(
      height: 1.0,
      color: Colors.grey[300],
    );
  }

  Widget _bottomNickNameView(String text) {
    return _actionEdit
        ? _bottomRightEditView(controller: nickNameController, hintText: "")
        : _bottomRightTextView(text);
  }

  Widget _bottomSignView(String text) {
    var hintStr = TextUtils.isEmpty(text) ? '这个人很懒...' : signature;
    return _actionEdit
        ? _bottomRightEditView(controller: signController, hintText: hintStr)
        : _bottomRightTextView(text);
  }

  Widget _bottomRightTextView(String text) {
    return TextView(text,
        padding: EdgeInsets.symmetric(horizontal: 8),
        margin: EdgeInsets.only(bottom: 8),
        textAlign: TextAlign.right,
        textSize: 18.0,
        textColor: Colors.black);
  }

  Widget _bottomRightEditView({TextEditingController controller, String hintText}) {
    return EditText(
        textAlign: TextAlign.right,
        controller: controller,
        padding: EdgeInsets.symmetric(horizontal: 8),
        hintText: hintText,
        margin: EdgeInsets.only(bottom: 8),
        textStyle: TextStyle(fontSize: 18.0, color: Colors.grey));
  }

  Widget _bottomQrView() {
    return ClickLayout(
        child: Container(
          child: Image.asset(
            'images/qr_pressed.png',
            width: 32.0,
            height: 32.0,
          ),
          padding: EdgeInsets.symmetric(horizontal: 8),
          margin: EdgeInsets.only(bottom: 8),
          alignment: Alignment.bottomRight,
        ),
        onPressed: _start2QrPage);
  }

//-------method----------
  void _start2QrPage() {
    Navigator.push(context,
        MaterialPageRoute(builder: (_) => QrCodeHome(username: username)));
  }

  void _queryByAccount() {
    Map<String, String> bodyParams = {'username': username};
    var http = HttpKit.getInstance(context: context, what: 2);
    http.callback(this);
    http.execute(method: 'queryUser', paramBody: bodyParams);
  }

  @override
  void onResult(int what, Object tag, String result) {
    try {
      Log.out(result);
      switch (what) {
        case 2:
          break;
        case 4:
          ReturnBean returnBean = ReturnBean.json2Bean(result);
          if (null == returnBean) {
            return;
          }
          String code = TextUtils.replaceNull(returnBean.code);
          String message = TextUtils.replaceNull(returnBean.message);
          showToast(message);
          if (TextUtils.equals("1", code)) {
            AccountBean accountBean = tag;
            setState(() {
              _actionEdit = false;
              nickName = accountBean.nickname;
              signature = accountBean.signature;
            });
          }
          break;
      }
    } catch (error) {
      onError(what, tag, error);
    }
  }

  @override
  void onError(int what, Object tag, String error) {
    showErrorPromptDialog("", error);
  }
}
